<?php
!defined('P_W') && exit('Forbidden');

class PW_PageCache {
	var $config;
	var $cache;
	var $signs = array();
	var $updateCache = array();
	function __construct($pageCacheConfig) {

		$this->config = $pageCacheConfig->getConfig();
		$this->_initSigns();

	}
	function PW_PageCache($type) {
		$this->__construct($type);
	}
	
	function getData($type) {
		$temp = $this->_getDataFromCache($type);
		
		if ($temp === false) {
			$temp = $this->_getDataFromReality($type);
		}
		!$temp && $temp = array();
		return $temp;
	}
	
	function getSigns() {
		return $this->signs;
	}

	function deleteCache($type) {
		$sign = $this->_getSign($type);
		$pagecache = $this->_getPageCacheService();
		$pagecache->deleteCache($sign);
	}
	
	function deleteThisCache() {
		foreach ($this->config as $key=>$value) {
			$this->deleteCache($key);
		}
	}
	
	function _getDataFromReality($type) {
		if (!isset($this->config[$type])) return false;
		$typeConfig = $this->config[$type];
		$typeDataImp = $this->_getTypeDataImp($typeConfig['type']);
		if (!$typeDataImp) return array();
		$temp = $typeDataImp->getData($typeConfig);
		$this->_updateCache($type,$temp);
		
		return $temp;
	}
	
	function _updateCache($type,$data) {
		global $timestamp;
	
		$cachetime = $this->config[$type]['cachetime'] ? $this->config[$type]['cachetime'] + $timestamp:0;
		$temp = array(
			'sign' => $this->_getSign($type),
			'type' => $this->_getCacheType($type),
			'data' => $data,
			'cachetime'=> $cachetime
		);
		$pagecache = $this->_getPageCacheService();
		$pagecache->relpace($temp);
	}
	
	function _getTypeDataImp($type) {
		$whiteTypes = array('comment','evaluations','feed','flash','group','housesort','imagetype','post','price','round','tag');
		if (!in_array($type,$whiteTypes)) return false;
		return House::loadClass('typedata'.$type,'model');
	}
	
	function _getDataFromCache($type) {
		global $timestamp;
		$key = $this->_getSign($type);
		if (isset($this->cache[$key]) && ($this->cache[$key]['cachetime'] == 0 || $this->cache[$key]['cachetime']>$timestamp)) {
			return $this->cache[$key]['data'];
		}
		return false;
	}
	
	function init() {
		$this->_initCache();
	}
	function _initSigns() {
		foreach ($this->config as $key=>$value) {
			$this->signs[$key] = $this->_getSign($key);
		}
	}
	function _initCache() {
		$pagecache = $this->_getPageCacheService();
		$this->cache = $pagecache->getDataBySigns($this->signs);
	}
	function _getSign($type) {
		if (!isset($this->config[$type])) Showmsg('this config is not defined');
		$temp = $this->config[$type];
		unset($temp['cachetime']);
		return md5(serialize($temp));
	}
	function _getCacheType($type) {
		if (!isset($this->config[$type])) Showmsg('this config is not defined');
		return $this->config[$type]['type'];
	}
	function _getPageCacheService() {
		return House::loadClass('pagecacheservice','service');
	}
}
?>